
package Server;

import CLIENT.Client;
import CLIENT.Message;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This Thread Listenes to new Clients that wants to join to this server and opens a conection with them
 * @author Yaniv Kalif
 */
public class NewClientsListenerThread implements Runnable
{
    ServerSocket socket = null;
    ServerMainChatPanel _creatorPanel;
    int _Connected=0;
    /**
     * Constructor for NewClientsListenerThread
     * @param socket - The Socket that the server listenes in
     * @param creatorPanel - the creator panel (ServerMainChatPanel)
     */
	public NewClientsListenerThread(ServerSocket socket,ServerMainChatPanel creatorPanel)
	{
		this.socket = socket;
                _creatorPanel=creatorPanel;
	}
        public void run()
        {
            while(_Connected<100) // MAX USERS 100
            {
                try
                {
                    Socket s = socket.accept();//waiting for a new _client
                    Client c = new Client(String.valueOf(_Connected),s);
                    _creatorPanel.AddClient(c);//add a new _client to the ServerPanel
                    SendID(c, String.valueOf(_Connected)); //sendID to the _client
                    ServerMessageListener msglistener = new ServerMessageListener(c, _creatorPanel);
                    Thread T=new Thread(msglistener);
                    T.start();
                    _Connected++;
                }
                catch (IOException ex)
                {
                    Logger.getLogger(NewClientsListenerThread.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
     /**
      * This Methos sends a new client that connected to the server it's ID in the system
      * @param c - The Client
      * @param msg - The string message
      * @throws IOException
      */
    public void SendID(Client c, String msg) throws IOException// throws IOException
    {

         Message m = new Message(msg,c.GetName());
         m.SetisSystemMessage(true);

        System.out.println("The server is sending");
        _creatorPanel._out[_Connected].writeObject(m);
        _creatorPanel._out[_Connected].flush();
    }
        
}
